const {
	Service
} = require('uni-cloud-router')

module.exports = class MarketingService extends Service {

	constructor(ctx) {
		super(ctx)
	}

	/**
	 * 根据秒杀活动ID获取数据
	 */
	async getSeckill(id) {
		const seckillRes = await this.db.collection('wmzmall-market-seckill').doc(id).field({
			name: true,
			goods_ids: true,
			goods_objs: true,
			seckill_end_time: true,
			seckill_begin_time: true,
			state: true,
			is_delete: true
		}).get();
		
		const [seckill] = seckillRes.data;
		if (!(seckill && seckill._id)) this.throw(`秒杀活动不存在`);
		
		const nowdate = Date.now();
		if (!(seckill.is_delete == 0 && seckill.state == '启用')) this.throw(`秒杀活动已停止`);
		if (!(seckill.seckill_begin_time <= nowdate && seckill.seckill_end_time >= nowdate)) this.throw(`秒杀活动已结束`);
		
		// 活动到期时间
		seckill.expires_time = (seckill.seckill_end_time - nowdate) / 1000;
		
		return seckill;
	}

	/**
	 * 根据拼团活动ID获取数据
	 * verify 验证活动是否有效
	 */
	async getGroup(id, verify = true) {
		const groupRes = await this.db.collection('wmzmall-market-groupbuy').doc(id).field({
			goods_id: true,
			goods_obj: true,
			goods_price: true,
			group_num: true,
			group_members: true,
			group_begin_time: true,
			group_end_time: true,
			group_time: true,
			state: true,
			is_delete: true
		}).get();
		
		const [group] = groupRes.data;
		if (!(group && group._id)) this.throw(`拼团活动不存在`);
		
		// 验证活动是否有效
		if (verify) {
			const nowdate = Date.now();
			if (!(group.is_delete == 0 && group.state == '启用')) this.throw(`拼团活动已停止`);
			if (!(group.group_begin_time <= nowdate && group.group_end_time >= nowdate)) this.throw(`拼团活动已结束`);
			
			// 活动到期时间
			group.expires_time = (group.group_end_time - nowdate) / 1000;
		}
		
		return group;
	}

	/**
	 * 根据拼团活动团长ID获取数据
	 * verify 验证是否过期
	 */
	async getGroupChief(id, verify = true) {
		const groupRes = await this.db.collection('wmzmall-market-groupbuy-member').doc(id).get();
		
		const [group] = groupRes.data;
		if (!(group && group._id)) this.throw(`当前拼单不存在`);
		
		if (group.is_delete == 1) this.throw(`当前拼单已停止`);
		if (verify) {
			if (group.state == '已取消') this.throw(`当前拼单活动已取消`);
			if (group.expire_time && Date.now() > group.expire_time) this.throw(`拼单活动已结束`);
		}
		
		return group;
	}

	/**
	 * 根据拼团活动订单ID获取数据
	 * verify 验证是否过期
	 */
	async getGroupChiefByOrder(id, verify = true) {
		const groupRes = await this.db.collection('wmzmall-market-groupbuy-member').where({ order_id: id }).limit(1).get();
		
		const [group] = groupRes.data;
		if (!(group && group._id)) this.throw(`您的开团不存在`);
		
		if (group.is_delete == 1) this.throw(`您的开团已停止`);
		if (verify) {
			if (group.state == '已取消') this.throw(`您的开团已取消`);
			if (group.expire_time && Date.now() > group.expire_time) this.throw(`拼单活动已结束`);
		}
		
		return group;
	}

}
